package com.cetc.ga.domain.repository;

import com.cetc.ga.domain.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;
import java.util.List;

/**
 * domain目录主要用于实体（Entity）与数据访问层（Repository）
 */
public interface UserRepository extends JpaRepository<UserEntity, Long> {
    /**
     * 1. 查询
     * 特定查询（通过证件号或名字）
     */
    //@Query(value = "select u from UserEntity u where u.userName like %:userName%")
    //@Query(value = "select u from UserEntity u where u.userName = :userName")
    @Query(value = "select u from UserEntity u where u.userName = ?1")
    List<UserEntity> findByName(@Param("userName") String userName);
    // 原生sql
    //@Query(value = "select * from users u where u.userName = ?1", nativeQuery = true)
    //List<UserEntity> findByName(String userName);

    //@Query("select u from UserEntity u where u.id = ?1")
    //UserEntity findOne(@Param("id") Long id);
    // 原生sql
    @Query(value = "select * from users u where u.id = ?1", nativeQuery = true)
    UserEntity findOne(Long id);
    @Query(value = "select * from users u where u.cardNo = ?1", nativeQuery = true)
    UserEntity findOne(String cardNo);

    /**
     * 2. 修改或更新
     * 完全覆盖
     */
    @Transactional
    @Modifying
    @Query("update UserEntity u SET u.userName = :userName,u.passWord = :passWord," +
            "u.userSex = :userSex, u.nickName = :nickName where u.cardNo = :cardNo")
    void update(@Param("cardNo") String cardNo, @Param("userName") String userName,
                @Param("passWord") String passWord, @Param("userSex") String userSex,
                @Param("nickName") String nickName);
    //void update(UserEntity userEntity);

    /**
     * 3. 删除
     */
    @Transactional
    @Modifying
    @Query("delete from UserEntity u where u.cardNo = :cardNo")
    void deleteByCardNo(@Param("cardNo") String cardNo);

    @Transactional
    @Modifying
    @Query("delete from UserEntity u where u.id = :id")
    void deleteById(@Param("id") Long id);

}
